<template>
  <a-modal :width="1200" v-model:visible="showHandleDeliveryOrder" title="签收" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <a-table
      class="table-two-line"
      ref="tableRef"
      row-key="id"
      :data="purchaseOrders"
      :span-method="spanMethodAll"
      :scroll="{
        y: 'calc(84vh - 160px)',
      }"
      :columns="tableColumns"
      :expandable="expandable"
      :default-expand-all-rows="true"
      size="mini"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template v-if="item.dataIndex == 'warehouseRealAmt'" #title>
            <a-popover content="实际签收数量必须小于等于入库数量">
              <p>
                <span>实际签收数量</span>
                <icon-question-circle />
              </p>
            </a-popover>
            <a-button style="height: 20px; overflow: hidden" type="text" @click="setAllAmt()">批量全部</a-button>
          </template>
          <template v-else-if="item.dataIndex == 'materialRealWeight'" #title>
            <a-popover content="签收时实际的材质重量。默认值=（入库材质重量/入库数量）*实际签收数量">
              <p>
                <span>实收材质重量(g)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template v-else-if="item.dataIndex == 'locationCode'" #title>
            <a-popover content="根据当前产品SKU已有库存，推荐货位">
              <p>
                <span>推荐上架货位</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template v-if="item.dataIndex == 'img'" #cell="{ record }">
            <div class="order-w flex-c">
              <div class="order-detail-item" style="width: 250px">
                <p>
                  <span class="label">收货仓：</span>
                  <span>{{ record.warehouseName }}({{ record.warehouseCode }})</span>
                </p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p>
                  <span class="label">入库单号：</span>
                  <span class="highlight">{{ record.billNo }}</span>
                </p>
              </div>
              <div class="order-detail-item">
                <p>
                  <span class="label">备注：</span>
                  <span>{{ record.remark }}</span>
                </p>
              </div>
            </div>
          </template>
        </a-table-column>
      </template>
      <template #expand-row="{ record }">
        <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :data="record.purchaseItems" size="mini" :pagination="false">
          <template #columns>
            <a-table-column :width="10" />
            <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'img'" #cell="option">
                <ImgPopover :src="option.record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                  </template>
                </ImgPopover>
              </template>
              <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                <TextLimit class="highlight cursor" :val="option.record.sku" @click="openInStorageItemDetail(option.record, record)" />
              </template>
              <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                <TextLimit :val="getProductSpecs(option.record)" />
              </template>
              <template v-else-if="item.dataIndex == 'props'" #cell="option">
                <template v-if="option.record.purchaseSpecsArr && option.record.purchaseSpecsArr.length">
                  <PurchasePropPopover :purchaseSpecsArr="option.record.purchaseSpecsArr" />
                </template>
              </template>
              <template v-else-if="item.dataIndex == 'warehouseRealAmt'" #cell="option">
                <div class="cell flex-c" style="width: 120px">
                  <a-input-number :precision="0" :min="0" v-model="option.record.warehouseRealAmt" style="width: 100px" placeholder="" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'warehouseRealAmt', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'materialRealWeight'" #cell="option">
                <p>{{ getMaterialRealWeight(option.record) }}</p>
              </template>
              <template v-else-if="item.dataIndex == 'locationCode'" #cell="option">
                <div class="cell flex-c" style="width: 120px">
                  <a-select v-model="option.record.location" value-key="id" style="width: 100px">
                    <a-option v-for="(location, i) in option.record.locationList" :key="i" :value="location" :label="location.locationCode" />
                  </a-select>
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'location', option.rowIndex, record.id)" />
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { signPurchaseReceipt } from '@/api/purchaseApplication'
  import { findAvailableLocation } from '@/api/inventory'
  import { parseJson } from '@/utils'
  import PurchasePropPopover from './purchasePropPopover.vue'

  onMounted(async () => {
    await getLocationList()
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: '规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '采购参数',
      dataIndex: 'props',
      width: 140,
    },
    {
      title: '申购人',
      dataIndex: 'salesmanName',
      width: 70,
    },
    {
      title: '店铺',
      dataIndex: 'shopName',
      width: 80,
    },

    {
      title: '入库数量',
      dataIndex: 'warehouseAmt',
      width: 70,
    },
    {
      title: '入库材质重量(g)',
      dataIndex: 'materialWeight',
      width: 70,
    },
    {
      title: '实际签收数量',
      dataIndex: 'warehouseRealAmt',
      width: 130,
    },
    {
      title: '实收材质重量(g)',
      dataIndex: 'materialRealWeight',
      width: 130,
    },
    {
      title: '上架货位',
      dataIndex: 'locationCode',
      width: 130,
    },
  ]

  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const showHandleDeliveryOrder = ref(props.isShow)
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const locationListMap = ref<any>({})

  // 获取货位列表
  async function getLocationList() {
    let itemParams: Array<any> = []
    props.list.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        itemParams.push({
          attribute: 'good',
          shopId: item.shopId,
          msku: item.msku,
          sku: item.sku,
          ownerId: item.salesmanId,
          warehouseCode: item.warehouseCode,
        })
      })
    })
    const res: any = await findAvailableLocation({ itemParams: itemParams })
    let list = res?.data || []
    locationListMap.value = {}
    list.forEach((item: any) => {
      let str = item.sku + item.shopId + item.warehouseCode + item.ownerId
      locationListMap.value[str] = item
    })
  }
  // 获取实收材质重量
  function getMaterialRealWeight(row: any) {
    return ((Number(row.materialWeight || 0) / Number(row.warehouseAmt)) * Number(row.warehouseRealAmt || 0)).toFixed(2)
  }

  // 添加初始化数据
  async function setDefaultData() {
    let list = JSON.parse(JSON.stringify(props.list))
    purchaseOrders.value = list.map((el: any) => {
      console.log(locationListMap.value)
      return {
        ...el,
        purchaseItems: el.billItems.map((item: any) => {
          let str = item.sku + item.shopId + item.warehouseCode + item.salesmanId
          console.log(str)
          item.locationList = locationListMap.value[str]?.locationList || []
          item.location = item.locationList?.[0] || null
          let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
          item.purchaseSpecsArr = Object.values(purchaseSpecs)
          item.warehouseRealAmt = item.warehouseAmt
          return item
        }),
      }
    })
    expandable.value.expandedRowKeys = purchaseOrders.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'img') {
      return { rowspan: 1, colspan: 11 }
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number, parentId: string) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.id === parentId)
    const newVal = item[key]
    purchaseOrders.value.forEach((el: any, index: number) => {
      if (index === parentIndex) {
        el.billItems.forEach((child: any, j: number) => {
          if (j > rowIndex) child[key] = newVal
        })
      } else if (index > parentIndex) {
        el.billItems.forEach((child: any) => {
          child[key] = newVal
        })
      }
    })
  }
  // 是否显示批量编辑按钮
  function showBatchIcon(parentId: string, childIndex: number) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.id === parentId)
    let parentLen = purchaseOrders.value.length
    return !(parentIndex === parentLen - 1 && childIndex === purchaseOrders.value[parentIndex].billItems.length - 1)
  }
  // 批量设置入库数
  function setAllAmt() {
    purchaseOrders.value.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        item.warehouseRealAmt = item.warehouseAmt
      })
    })
  }
  // 关闭
  function closedDialog() {
    showHandleDeliveryOrder.value = false
    emit('closed')
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 保存
  async function submitData() {
    let signItemParams: Array<any> = []
    purchaseOrders.value.forEach((el: any) => {
      el.billItems.forEach((child: any) => {
        signItemParams.push({
          billId: el.id,
          id: child.id,
          materialRealWeight: getMaterialRealWeight(child),
          warehouseRealAmt: child.warehouseRealAmt,
          locationCode: child.location?.locationCode,
          locationId: child.location?.id,
        })
      })
    })
    let res: any = await signPurchaseReceipt({ signItemParams })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
